package com.yunsc.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.store.dao.YunscExpressDao;
import com.yunsc.store.dto.QueryPageDTO;
import com.yunsc.store.dto.StoreExpressDTO;
import com.yunsc.store.entity.YunscExpressEntity;
import com.yunsc.store.service.YunscExpressService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("yunscExpressService")
public class YunscExpressServiceImpl extends ServiceImpl<YunscExpressDao, YunscExpressEntity> implements YunscExpressService {


    @Override
    public List<YunscExpressEntity> queryExpressList(Integer storeId) {
        return this.list(new QueryWrapper<YunscExpressEntity>().eq("store_id", storeId));
    }

    @Override
    public PageResult<YunscExpressEntity> queryExpressPage(QueryPageDTO param, Integer storeId) {
        LambdaQueryWrapper<YunscExpressEntity> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(param.getSearch()), YunscExpressEntity::getExpressName, param.getSearch());
        Page<YunscExpressEntity> pageResult = this.page(new Page<>(param.getPage(), param.getPageSize()), lqw);
        List<YunscExpressEntity> records = pageResult.getRecords();
        return PageResult.formatPageResult(records, param.getPage(), param.getPageSize(), pageResult.getTotal());

    }

    @Override
    public void addExpress(StoreExpressDTO params, Integer storeId) {
        YunscExpressEntity expressEntity = new YunscExpressEntity();
        BeanUtils.copyProperties(params.getForm(), expressEntity);
        expressEntity.setStoreId(storeId);
        this.save(expressEntity);
    }

    @Override
    public void deleteExpress(Integer expressId) {
        YunscExpressEntity express = this.getById(expressId);
        if (express == null) {
            throw new YunscException("物流公司不存在");
        }
        this.removeById(expressId);
    }

    @Override
    public void editExpress(StoreExpressDTO params) {
        Integer expressId = params.getExpressId();
        YunscExpressEntity expressEntity = this.getById(expressId);
        if (expressEntity == null) {
            throw new YunscException("物流公司不存在");
        }
        BeanUtils.copyProperties(params.getForm(), expressEntity);
        expressEntity.setExpressId(expressId);
        this.updateById(expressEntity);
    }
}